package jkclient

import (
	"encoding/json"
	"jkgo/jk/jklog"
	b "findService/ss/servicebase"
	"time"
)

var mqttSeq uint

func NewClientIoT(addr string, port int) (*DemoClient, error) {
	c := &DemoClient{}

	c.iotclient, _ = b.NewSSIoTClient(addr, port, service_selfname)
	c.iotclient.SetMsgHandle(c)
	go c.iotclient.Connect()

	return c, nil
}

func (sc *DemoClient) IoTDealMessage(topic, msg string) error {
	jklog.L().Debugln("topic ", topic, ", msg ", msg)
	return nil
}

func (sc *DemoClient) IoTPub(topic, data string) {
	jklog.L().Debugln("topic ", topic, " , data ", data)
	err := sc.iotclient.Pub(topic, data)
	if err != nil {
		jklog.L().Errorln("error send topic")
	}
}

func (sc *DemoClient) IoTStatusReport(status string) {
	jklog.L().Infoln("iot status changed to status ", status)

	if status == "connected" {
		mp := b.MsgPayload{
			Data: "justtest",
		}
		mp.ID = "jkclient"
		mqttSeq = b.JKSeqGet(mqttSeq)
		mp.Seq = mqttSeq
		mp.Timestamp = time.Now().UnixNano() / 1000000
		str, _ := json.Marshal(mp)
		sc.IoTPub("/jkimgproc/imgdetect", string(str))

		sc.iotclient.Sub("/jkimgproc/response")
	}
}
